package tsing.javase.dinamicproxy.phone;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Author Tsing/吴清平
 * @Date 2022/10/13 17:11
 * @Version 1.0
 */
public class PhoneProxy implements InvocationHandler {
    private Object target;

    public Object getInstance(Object object){
        this.target = object;
        return  Proxy.newProxyInstance(object.getClass().getClassLoader(),object.getClass().getInterfaces(),this);

    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("方法调用前");
        Object result = method.invoke(target, args);
        System.out.println("方法调用后");
        return result;
    }

    //调用测试
    public static void main(String[] args) {
        PhoneProxy phoneProxy = new PhoneProxy();  // 代理类
//        Phone instance = (Phone) phoneProxy.getInstance(new Xiaomi()); //获得动态代理对象
        Phone instance = (Phone) phoneProxy.getInstance(new Iphone()); //获得动态代理对象
        instance.sellPhone();

    }
}
